package com.sikaryofficial.knowledge.config;

import com.sikaryofficial.common.core.context.SecurityContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author qinjinyuan
 * @date 2023/9/2
 */
@Configuration
@Slf4j
public class ThreadPoolConfig {
    // 线程池维护线程所允许的空闲时间
    @Value("${thread-pool-config.keepAliveSeconds}")
    private int keepAliveSeconds;
    // 队列最大长度
    @Value("${thread-pool-config.queueCapacity}")
    private int queueCapacity;

    @Bean("asyncTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(4);
        // 设置最大线程数
        executor.setMaxPoolSize(4);
        // 设置队列容量
        executor.setQueueCapacity(32);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置默认线程名称
        executor.setThreadNamePrefix("hismk-knowledge-async");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 该方法用来设置 线程池关闭 的时候 等待 所有任务都完成后，再继续 销毁 其他的 Bean，这样这些 异步任务 的 销毁 就会先于 数据库连接池对象 的销毁。
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 该方法用来设置线程池中 任务的等待时间，如果超过这个时间还没有销毁就 强制销毁，以确保应用最后能够被关闭，而不是阻塞住。
        executor.setAwaitTerminationSeconds(60);
        // 设置任务的装饰
        executor.setTaskDecorator(new ContextCopyDecorator());
        executor.initialize();
        return executor;
    }

    /**
     * 线程池任务-上下文拷贝 装饰器
     */
    static class ContextCopyDecorator implements TaskDecorator {
        @Nonnull
        @Override
        public Runnable decorate(@Nonnull Runnable runnable) {
            RequestAttributes context = RequestContextHolder.currentRequestAttributes();
            Map<String, Object> threadLocalMap = SecurityContextHolder.getLocalMap();

            Map<String, String> mdcContextMap = MDC.getCopyOfContextMap();
            return () -> {
                try {
                    RequestContextHolder.setRequestAttributes(context);
                    SecurityContextHolder.setLocalMap(threadLocalMap);
                    if(Objects.nonNull(mdcContextMap)){
                        MDC.setContextMap(mdcContextMap);
                    }
                    runnable.run();
                } finally {
                    RequestContextHolder.resetRequestAttributes();
                    SecurityContextHolder.remove();
                    MDC.clear();
                }
            };
        }
    }


}
